<template>
  <xn-dialog
    custom-class="user-rest-pwd-dialog"
    :title="(isForceEdit && '重置密码') || '修改密码'"
    :visible.sync="selfVisible"
    :close-on-press-escape="!isForceEdit"
    :show-close="!isForceEdit"
    @close="onDialogHide">
    <div class="content">
      <el-alert
        class="tips"
        v-if="isForceEdit"
        title="提示：首次登录系统需先重置密码！"
        type="info"
        :closable="false"></el-alert>
      <div class="reset-form">
        <el-form ref="form" :model="form" label-width="100px" size="medium" label-suffix="：" :rules="rules">
          <el-form-item v-if="!isForceEdit" label="原密码" prop="oldPwd">
            <el-input
              type="newPwd"
              maxlength="16"
              placeholder="请输入原密码"
              v-model="form.oldPwd"
              show-newPwd></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="newPwd">
            <el-input
              type="newPwd"
              maxlength="16"
              placeholder="请设置新密码"
              v-model="form.newPwd"
              show-newPwd></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="repeatPwd">
            <el-input
              type="newPwd"
              maxlength="16"
              placeholder="请确认新密码"
              v-model="form.repeatPwd"
              @keyup.enter.native="onSubmit"
              show-newPwd></el-input>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="footer" slot="footer">
      <el-button v-if="!isForceEdit" type="default" @click="selfVisible = false">取消</el-button>
      <el-button type="primary" @click="onSubmit">确定</el-button>
    </div>
  </xn-dialog>
</template>
<script>
import { updateLoginPassword } from '@api/modules/user.js'
import XnDialog from '@com/xnDialog.vue'
export default {
  name: 'UserResetPwdDialog',
  components: {
    XnDialog,
  },
  props: {
    visible: {
      type: Boolean,
    },
  },
  data() {
    const validateNewPwd = (rule, value, callback) => {
      /**
       * 密码规则：1、长度8~16；
       * 2、包含字母及数字；
       * 3、不能和用户名相同。
       */
      const pattern = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,16}$/
      if (value === this.form.oldPwd) {
        callback(new Error('新密码不能与原密码相同!'))
      } else if (!pattern.test(value)) {
        callback(new Error('密码长度8~16，包含字母及数字!'))
      } else if (value === localStorage.getItem('BBCS__loginName')) {
        callback(new Error('不能和用户名相同!'))
      } else {
        callback()
      }
    }
    // 此处即表单发送之前验证  验证新密码与再次确认
    const validatePwdConfirm = (rule, value, callback) => {
      if (value !== this.form.newPwd) {
        callback(new Error('与新密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      selfVisible: false,
      isForceEdit: false,
      form: {
        oldPwd: '',
        newPwd: '',
        repeatPwd: '',
        type: '1',
      },
      rules: {
        // 验证规则
        oldPwd: [
          {
            required: true,
            message: '请输入原密码',
            trigger: 'blur',
          },
        ],
        newPwd: [
          {
            required: true,
            message: '请设置新密码',
            trigger: 'blur',
          },
          {
            validator: validateNewPwd,
            trigger: 'blur',
          },
        ],
        repeatPwd: [
          {
            required: true,
            message: '请确认新密码',
            trigger: 'blur',
          },
          {
            validator: validatePwdConfirm,
            trigger: 'blur',
          },
        ],
      },
    }
  },
  computed: {
    userInfo() {
      return this.$store.getters.userInfo
    },
  },
  watch: {
    visible(visible) {
      this.selfVisible = visible
      if (!visible) {
        this.form.oldPwd = ''
        this.form.newPwd = ''
        this.form.repeatPwd = ''
      }
    },
    userInfo: {
      immediate: true,
      handler() {
        if (this.userInfo) {
          const shouldReset = this.userInfo.initPassword && this.userInfo.initPassword !== '1'
          this.selfVisible = shouldReset
          if (shouldReset) {
            this.isForceEdit = true
            this.form.oldPwd = window.atob(localStorage.getItem('BBCS__loginPassword'))
          }
        }
      },
    },
  },
  created() {},
  mounted() {},
  methods: {
    onDialogHide() {
      this.$emit('update:visible', false)
      this.$emit('closed')
    },
    onSubmit() {
      this.$refs.form.validate(valid => {
        // valid 全为 true即执行以下操作
        if (valid) {
          updateLoginPassword(this.form).then(res => {
            if (res.status === 200 || res.status === 200) {
              this.$message.success('密码修改成功！')
              this.selfVisible = false
              this.userInfo.initPassword = '1'
              this.$store.commit('setUserInfo', this.userInfo)
              // 如果当前是记住密码，更新本地的密码
              // if (localStorage.getItem('EFF_TS_remember') === 'true') {
              localStorage.setItem('BBCS__loginPassword', window.btoa(this.form.newPwd))
              // }
            }
          })
        }
      })
    },
  },
}
</script>
<style lang="scss" scoped>
.user-rest-pwd-dialog {
  ::v-deep &.el-dialog {
    width: 500px !important;
  }
  .content {
    height: 100%;
    .tips {
      margin-top: 10px;
    }
    .reset-form {
      padding-top: 20px;
      padding-right: 30px;
    }
    .footer {
      text-align: center;
      .btn-sure {
        padding: 10px 50px;
      }
    }
  }
}
</style>
